﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MatchCore;
using Net.Messgae;

public class ControllerManager : MonoBehaviour
{
    public ShootController shootController;
    public DirectionController directionController;

    private bool enable = false;

    private uint inputFrameId = 0;

    void Awake()
    {
        shootController.onShooting += OnShooting;
    }

    void OnDestroy()
    {
        shootController.onShooting -= OnShooting;
    }

    public void SetEnable(bool enable)
    {
        this.enable = enable;
        shootController.enable = enable;
        directionController.enable = enable;
    }

    void Update() 
    {
        if(!enable)
        {
            return;
        }

        uint curFrameId = LogicManager.Instance().GetCurFrameId();

        if(inputFrameId != curFrameId)
        {   
            inputFrameId = curFrameId;

            var curDir = directionController.CurDir;

            OnDirChanged(curDir);
        }
    }

    void OnDirChanged(UnityEngine.Vector2 dir)
    {
        if(0 == dir.y)
        {
            return;
        }

        uint cmd = Command.SetCommandType(0,CommandType.Move);
        if(dir.y < 0)
        {
            cmd = Command.SetMoveDirType(cmd,MoveDirType.Down);
        }
        else
        {
            cmd = Command.SetMoveDirType(cmd,MoveDirType.Up);
        }
        SendCmd(cmd);
    }

    void OnShooting()
    {
        SendCmd(Command.SetCommandType(0,CommandType.Shoot));
    }

    void SendCmd(uint cmd)
    {
        MessageInputFrame input = new MessageInputFrame();
        input.Frame = new FrameData();
        input.Frame.FrameId = LogicManager.Instance().GetCurFrameId() + 1;
        PlayerFrameData data = FrameHelper.MakePlayerFrameData(Model.Instance().roomModel.roomInfo.Index,cmd);
        input.Frame.Datas.Add(data);
        Model.Instance().msgHandler.SendMessage(MessageId.InputFrame,input,true);
    }
}
